$(function() {
	var app = angular.module('calApp', [ 'toaster', 'ngAnimate' ]);
	app
			.controller(
					'calCtrl',
					function($scope, $http, $filter, toaster) {
						// 默认不显示模态框，提示
						$scope.isHideModal = true;
						$scope.currentDeleteCalendarId = null;
						// 只允许输入数字和小数点
						$scope.clearNoNum = function(obj) {
							// 先把非数字的都替换掉，除了数字和.
							obj = obj.replace(/[^\d.]/g, "");
							// 必须保证第一个为数字而不是.
							obj = obj.replace(/^\./g, "");
							// 保证只有出现一个.而没有多个.
							obj = obj.replace(/\.{2,}/g, "");
							// 保证.只出现一次，而不能出现两次以上
							$scope.work_time = obj.replace(".", "$#$").replace(
									/\./g, "").replace("$#$", ".");
						}
						// 导出所有人的工作日志
						$scope.monthexportfun = function() {
							window.location.href = "cal/monthexport.do?month="
									+ $scope.monthexport;
							return;

						};
						// 添加个人工作日志取消
						$scope.isShowDayEventCancle = function() {
							$scope.work_time = "";
							document.getElementById("isShowDayEvent").style.display = "none";
						};
						// 添加个人工作日志
						$scope.addDayEvent = function() {
							currentprojectname = $scope.currentprojectname;
							work_time = $scope.work_time
							if ($scope.work_time == undefined
									|| $scope.work_time == '') {
								work_time = 0;
							}
							work_content = '';
							if ($scope.work_content != undefined
									&& $scope.work_content != '') {
								work_content = encodeURI($scope.work_content)
							}

							// 添加个人日志
							$http(
									{
										method : 'POST',
										url : "cal/addMyCalendarForOneDay.do",
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded'
										},
										params : {
											date : $scope.currentdate,
											work_time : work_time,
											currentprojectname : encodeURI($scope.currentprojectname),
											work_content : work_content
										},
									})
									.success(
											function(data) {// 这里的data，就是后台传递过来的数据
												if (data.tag == 'success') {
													$scope
															.isShowDayEventCancle();
													copiedEventObject = {};

													copiedEventObject.title = work_content == '' ? currentprojectname
															+ ":"
															+ work_time
															+ "小时"
															: currentprojectname
																	+ ":"
																	+ work_time
																	+ "小时";
													copiedEventObject.id = data.id;
													copiedEventObject.start = $scope.currentdate;
													copiedEventObject.end = $scope.currentdate;
													copiedEventObject.allDay = true;
													copiedEventObject.className = $(
															this).attr(
															"data-class");
													$('#calendar')
															.fullCalendar(
																	'renderEvent',
																	copiedEventObject,
																	false);
												} else {
													toaster.pop({
														type : 'error',
														title : '提示',
														body : "添加失败",
														timeout : 2000
													});
												}
											}).error(
											function(data, status, headers,
													config) {
												toaster.pop({
													type : 'error',
													title : '提示',
													body : "请求出错了",
													timeout : 2000
												});
											});
						}
						// 删除日程取消
						$scope.deleteCalendarCancle = function() {
							$scope.currentDeleteCalendarId = null;
							$scope.isHideModal = true;
							document.getElementById("static").style.display = "none";
						};
						// 删除日程
						$scope.deleteCalendarOK = function() {
							$http(
									{
										method : 'POST',
										url : "cal/deleteMyCalendar.do",
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded'
										},
										params : {
											id : $scope.currentDeleteCalendarId
										},
									})
									.success(
											function(data) {// 这里的data，就是后台传递过来的数据
												if (data.tag == 'success'
														&& $scope.currentDeleteCalendarId != null) {
													$('#calendar')
															.fullCalendar(
																	'removeEvents',
																	function(
																			event) {
																		return event.id == $scope.currentDeleteCalendarId;
																	});
													$scope.currentDeleteCalendarId = null;
													document
															.getElementById("static").style.display = "none";
													$scope.isHideModal = true;
												} else {
													toaster.pop({
														type : 'error',
														title : '提示',
														body : "删除个人日程失败",
														timeout : 2000
													});
												}
											}).error(
											function(data, status, headers,
													config) {
												toaster.pop({
													type : 'error',
													title : '提示',
													body : "请求出错了",
													timeout : 2000
												});
											});
						}
						$scope.msgbox = function() {
							toaster.pop({
								type : 'error',
								title : '提示',
								body : "请输入内容",
								timeout : 1000
							});
						}
						// 切换下属的时候重新初始化日历
						$scope.subordinatesChange = function() {
							$scope.initCalendar();
							if ($scope.currentUsersid == $scope.subordinate) {
								$scope.initTitle();
							}
						}

						// 初始化
						$scope.init = function() {
							/*
							 * App.addResponsiveHandler(function() {
							 * Calendar.initCalendar(); });
							 */
							$('.page-sidebar .sidebar-toggler').click(
									function() {
										$scope.initCalendar();
									});
							$scope.initProjectName();
							$scope.initSubordinate();
							$scope.initCalendar();
							$scope.initTitle();
						}
						// 初始化当前所有项目的名字
						$scope.initProjectName = function() {
							var getTimestamp = new Date().getTime();
							$http(
									{
										method : 'GET',
										url : "cal/selectCurrentProject.do?time="
												+ getTimestamp,
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded',
											'timestamp' : getTimestamp
										},
									})
									.success(
											function(data) {// 这里的data，就是后台传递过来的数据
												if (data.tag == 'success') {
													$scope.projectnamelist = data.result;
													if ($scope.projectnamelist.length > 0) {
														$scope.currentprojectname = $scope.projectnamelist[0];
													} else {
														toaster.pop({
															type : 'error',
															title : '提示',
															body : "未获取到项目名",
															timeout : 2000
														});
													}
												}
											}).error(
											function(data, status, headers,
													config) {
												toaster.pop({
													type : 'error',
													title : '提示',
													body : "请求出错了",
													timeout : 2000
												});
											});
						}
						// 初始化下属信息。
						$scope.initSubordinate = function() {
							var getTimestamp = new Date().getTime();
							$http(
									{
										method : 'GET',
										url : "cal/selectSubordinate.do?time="
												+ getTimestamp,
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded',
											'timestamp' : getTimestamp
										},
									})
									.success(
											function(data) {// 这里的data，就是后台传递过来的数据
												if (data.tag == 'success') {
													$scope.subordinates = data.result;
													if ($scope.subordinates.length > 1) {
														$scope.isShowChoice = true;
														$scope.currentUsersid = $scope.subordinates[0].usersid;
														$scope.subordinate = $scope.subordinates[0].usersid;
													}
												} else {
													toaster.pop({
														type : 'error',
														title : '提示',
														body : "未获取到下属信息",
														timeout : 2000
													});
												}
											}).error(
											function(data, status, headers,
													config) {
												toaster.pop({
													type : 'error',
													title : '提示',
													body : "请求出错了",
													timeout : 2000
												});
											});
						}
						// 初始化个人title
						$scope.initTitle = function() {
							var getTimestamp = new Date().getTime();
							$http(
									{
										method : 'GET',
										url : "cal/selectMyEvents.do?time="
												+ getTimestamp,
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded',
											'timestamp' : getTimestamp
										},
									})
									.success(
											function(data) {// 这里的data，就是后台传递过来的数据
												if (data.tag == 'success') {
													for (var i = 0; i < data.result.length; i++) {
														$scope
																.addEvent(data.result[i].title);
													}
												} else {
													toaster.pop({
														type : 'error',
														title : '提示',
														body : "查询个人title失败",
														timeout : 2000
													});
												}
											}).error(
											function(data, status, headers,
													config) {
												toaster.pop({
													type : 'error',
													title : '提示',
													body : "请求出错了",
													timeout : 2000
												});
											});
						}
						// 初始化拖拽
						$scope.initDrag = function(el) {
							// create an Event Object
							// (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
							// it doesn't need to have a start or end
							var eventObject = {
								title : $.trim(el.text())
							// use the element's text as the event title
							};
							// store the Event Object in the DOM element so we
							// can get to it
							// later
							el.data('eventObject', eventObject);
							// make the event draggable using jQuery UI
							el.draggable({
								zIndex : 999,
								revert : true, // will cause the event to go
								// back to its
								revertDuration : 0
							// original position after the drag
							});
						}
						// 添加日程
						$scope.addEvent = function(title) {
							var html = $('<div class="external-event label">'
									+ title + '</div>');
							jQuery('#event_box').append(html);
							$scope.initDrag(html);
						}
						$scope.eventAddClick = function() {
							// 添加个人事件
							var title = $('#event_title').val().trim();
							if (title.length == 0) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请输入内容",
									timeout : 1000
								});
							} else {
								$http(
										{
											method : 'POST',
											url : "cal/insertMyEvents.do",
											headers : {
												'Content-Type' : 'application/x-www-form-urlencoded'
											},
											params : {
												title : encodeURI(title)
											},
										}).success(function(data) {// 这里的data，就是后台传递过来的数据
									if (data == 'true') {
										$scope.addEvent(title);
									} else {
										toaster.pop({
											type : 'error',
											title : '提示',
											body : "添加失败",
											timeout : 2000
										});
									}
								})
										.error(
												function(data, status, headers,
														config) {
													toaster.pop({
														type : 'error',
														title : '提示',
														body : "请求出错了",
														timeout : 2000
													});

												});
							}
						}
						// 初始化日历
						$scope.initCalendar = function() {
							if (!jQuery().fullCalendar) {
								return;
							}
							// angular.element(document.getElementById('calApp')).scope().msgbox();
							var date = new Date();
							var d = date.getDate();
							var m = date.getMonth();
							var y = date.getFullYear();
							var h = {};
							if (App.isRTL()) {
								if ($('#calendar').parents(".portlet").width() <= 720) {
									$('#calendar').addClass("mobile");
									h = {
										right : 'title, prev, next',
										center : '',
										right : 'agendaDay, agendaWeek, month, today'
									};
								} else {
									$('#calendar').removeClass("mobile");
									h = {
										right : 'title',
										center : '',
										left : 'agendaDay, agendaWeek, month, today, prev,next'
									};
								}
							} else {
								if ($('#calendar').parents(".portlet").width() <= 720) {
									$('#calendar').addClass("mobile");
									h = {
										left : 'title, prev, next',
										center : '',
										right : 'today,month,agendaWeek,agendaDay'
									};
								} else {
									$('#calendar').removeClass("mobile");
									h = {
										left : 'title',
										center : '',
										right : 'prev,next,today,month,agendaWeek,agendaDay'
									};
								}
							}

							$('#external-events div.external-event').each(
									function() {
										$scope.initDrag($(this))
									});
							// predefined events
							$('#event_box').html("");
							$('#calendar').fullCalendar('destroy'); // destroy
							// the
							// calendar
							$("#calendar")
									.fullCalendar(
											{
												height : 550,
												aspectRatio : 1.5,
												weekends : true,
												firstDay : 1,
												weekMode : 'liquid',
												weekNumbers : true,
												monthNames : [ '一月', '二月',
														'三月', '四月', '五月', '六月',
														'七月', '八月', '九月', '十月',
														'十一月', '十二月' ],
												monthNamesShort : [ '一月', '二月',
														'三月', '四月', '五月', '六月',
														'七月', '八月', '九月', '十月',
														'十一月', '十二月' ],
												dayNames : [ '周日', '周一', '周二',
														'周三', '周四', '周五', '周六' ],
												dayNamesShort : [ '周日', '周一',
														'周二', '周三', '周四', '周五',
														'周六' ],
												weekNumberTitle : "周",
												selectable : true,
												// 控制是否显示月、周、日
												// header : h,
												slotMinutes : 15,
												editable : true,
												droppable : true, // this
												// 日程点击事件
												eventClick : function(calEvent,
														jsEvent, view) {
													document
															.getElementById("static").style.display = "block";
													$scope.isHideModal = false;
													$scope.currentDeleteCalendarId = calEvent.id;
													$http(
															{
																method : 'POST',
																url : "cal/selectCalendarForOne.do",
																headers : {
																	'Content-Type' : 'application/x-www-form-urlencoded'
																},
																params : {
																	id : $scope.currentDeleteCalendarId
																},
															})
															.success(
																	function(
																			data) {// 这里的data，就是后台传递过来的数据
																		if (data.tag == 'success') {
																			$scope.currentEventResult = data.result[0];
																		} else {

																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "查询失败",
																						timeout : 2000
																					});
																		}
																	})
															.error(
																	function(
																			data,
																			status,
																			headers,
																			config) {
																		toaster
																				.pop({
																					type : 'error',
																					title : '提示',
																					body : "请求出错了",
																					timeout : 2000
																				});
																	});
												},
												// 日历点击事件
												dayClick : function(date,
														allDay, jsEvent, view) {
													$scope.currentdate = date;
													document
															.getElementById("isShowDayEvent").style.display = "block";
												},
												// 日程调整
												eventResize : function(event,
														dayDelta, minuteDelta,
														revertFunc) {
													$http(
															{
																method : 'POST',
																url : "cal/updateMyCalendarForResize.do",
																headers : {
																	'Content-Type' : 'application/x-www-form-urlencoded'
																},
																params : {
																	id : event.id,
																	dayDelta : dayDelta
																},
															})
															.success(
																	function(
																			data) {// 这里的data，就是后台传递过来的数据
																		if (data.tag == 'success') {
																		} else {
																			revertFunc();
																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "拖动个人日程失败",
																						timeout : 2000
																					});
																		}
																	})
															.error(
																	function(
																			data,
																			status,
																			headers,
																			config) {
																		toaster
																				.pop({
																					type : 'error',
																					title : '提示',
																					body : "请求出错了",
																					timeout : 2000
																				});
																	});
												},
												// 拖动，日历内拖动
												eventDrop : function(event,
														dayDelta, minuteDelta,
														allDay, revertFunc) {
													//
													$http(
															{
																method : 'POST',
																url : "cal/updateMyCalendarForDrop.do",
																headers : {
																	'Content-Type' : 'application/x-www-form-urlencoded'
																},
																params : {
																	id : event.id,
																	dayDelta : dayDelta
																},
															})
															.success(
																	function(
																			data) {// 这里的data，就是后台传递过来的数据
																		if (data.tag == 'success') {

																		} else {
																			revertFunc();
																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "拖动个人日程失败",
																						timeout : 2000
																					});
																		}
																	})
															.error(
																	function(
																			data,
																			status,
																			headers,
																			config) {
																		toaster
																				.pop({
																					type : 'error',
																					title : '提示',
																					body : "请求出错了",
																					timeout : 2000
																				});
																	});
												},
												// 拖动事件--拖入
												drop : function(date, allDay) {
													var originalEventObject = $(
															this).data(
															'eventObject');
													var copiedEventObject = $
															.extend({},
																	originalEventObject);
													// 添加个人日志
													$http(
															{
																method : 'POST',
																url : "cal/addMyCalendar.do",
																headers : {
																	'Content-Type' : 'application/x-www-form-urlencoded'
																},
																params : {
																	title : encodeURI(copiedEventObject.title),
																	allDay : allDay,
																	start : date
																},
															})
															.success(
																	function(
																			data) {// 这里的data，就是后台传递过来的数据
																		if (data.tag == 'success') {
																			copiedEventObject.id = data.id;
																			copiedEventObject.start = date;
																			copiedEventObject.allDay = allDay;
																			copiedEventObject.className = $(
																					this)
																					.attr(
																							"data-class");
																			$(
																					'#calendar')
																					.fullCalendar(
																							'renderEvent',
																							copiedEventObject,
																							false);
																		} else {
																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "拖动失败",
																						timeout : 2000
																					});
																		}
																	})
															.error(
																	function(
																			data,
																			status,
																			headers,
																			config) {
																		toaster
																				.pop({
																					type : 'error',
																					title : '提示',
																					body : "请求出错了",
																					timeout : 2000
																				});
																	});

													if ($('#drop-remove').is(
															':checked')) {
														$(this).remove();
														$http(
																{
																	method : 'POST',
																	url : "cal/deleteMyEvents.do",
																	headers : {
																		'Content-Type' : 'application/x-www-form-urlencoded'
																	},
																	params : {
																		title : encodeURI(copiedEventObject.title)
																	},
																})
																.success(
																		function(
																				data) {// 这里的data，就是后台传递过来的数据
																			if (data.tag == 'success') {
																			} else {
																				toaster
																						.pop({
																							type : 'error',
																							title : '提示',
																							body : "删除失败",
																							timeout : 2000
																						});
																			}
																		})
																.error(
																		function(
																				data,
																				status,
																				headers,
																				config) {
																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "请求出错了",
																						timeout : 2000
																					});
																		});
													}
												},
												// 查询个人日志
												events : function(start, end,
														callback) {
													var getTimestamp = new Date()
															.getTime();
													$http(
															{
																method : 'GET',
																url : "cal/selectMyCalendar.do?time="
																		+ getTimestamp,
																headers : {
																	'Content-Type' : 'application/x-www-form-urlencoded',
																	'time' : getTimestamp
																},
																params : {
																	usersid : $scope.subordinate
																},
															})
															.success(
																	function(
																			data) {// 这里的data，就是后台传递过来的数据
																		if (data.tag == 'success') {
																			var events = [];
																			$(
																					'#calendar')
																					.each(
																							function() {
																								for (var a = 0; a < data.result.length; a++) {
																									var newDate = new Date();
																									if (data.result[a].endtime != null) {

																										newDate
																												.setTime(data.result[a].endtime);
																										data.result[a].endtime = newDate
																												.format('yyyy-MM-dd');
																									}
																									newDate
																											.setTime(data.result[a].start);

																									data.result[a].start = newDate
																											.format('yyyy-MM-dd');

																									events
																											.push({
																												start : data.result[a].start,
																												title : data.result[a].title,
																												id : data.result[a].id,
																												allDay : data.result[a].allday == 1 ? false
																														: true,
																												end : data.result[a].endtime == null ? null
																														: data.result[a].endtime
																											});
																								}
																							});
																			callback(events);
																		} else {
																			toaster
																					.pop({
																						type : 'error',
																						title : '提示',
																						body : "拖动失败",
																						timeout : 2000
																					});
																		}
																	})
															.error(
																	function(
																			data,
																			status,
																			headers,
																			config) {
																		toaster
																				.pop({
																					type : 'error',
																					title : '提示',
																					body : "请求出错了",
																					timeout : 2000
																				});
																	});
												}
											});
						}
					})
	// init();
})

String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
};
Date.prototype.format = function(format) {
	var date = {
		"M+" : extra(this.getMonth() + 1),
		"d+" : extra(this.getDate()),
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '')
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k]
					: ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}
// 补位函数。
function extra(x) {
	// 如果传入数字小于10，数字前补一位0。
	if (x < 10) {
		return "0" + x;
	} else {
		return x;
	}
}